package com.ruoyi.ruoyiqywechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.qy.exception.CrmebException;
import com.ruoyi.common.qy.oss.OssService;
import com.ruoyi.common.qy.vo.DouYinVideoVo;
import com.ruoyi.common.redis.utils.RedisUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ruoyiqywechat.domain.UserMembership;
import com.ruoyi.ruoyiqywechat.service.DouyinService;
import com.ruoyi.ruoyiqywechat.service.IUserMembershipService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class DouyinServiceImpl implements DouyinService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IUserMembershipService userMembershipService;
    @Override
    public Boolean queryWatchVideoNum(HttpServletRequest request,String videoId) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        // 使用当天日期作为key的一部分，确保每天自动刷新
        String cacheKey = CacheConstants.WATCH_VIDEO_DOU_YIN_NUM + userId ;
        Long watchCount = redisUtil.incr(cacheKey, 1L);
        Long decr = redisUtil.decr(cacheKey, 1L);
        System.out.println("用户："+userId+videoId+"观看次数"+decr);
        //判断当前是否是会员
        //判断当前会员是否重复，如果是则不允许重复会员充值
        QueryWrapper<UserMembership> userMembershipQueryWrapper = new QueryWrapper<>();
        userMembershipQueryWrapper.lambda().eq(UserMembership::getUserId,userId)
                .eq(UserMembership::getStatus,1);
        UserMembership one = userMembershipService.getOne(userMembershipQueryWrapper);
        if(one != null){
            return false;
        }

        return decr <= 1;
    }

    @Override
    public void addWatchVideoNum(HttpServletRequest request,String videoId) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        String cacheKey = CacheConstants.WATCH_VIDEO_DOU_YIN_NUM + userId ;
        redisUtil.incr(cacheKey, 1L);
    }


    @Override
    public void saveDouYinVideo(String userId, String videoId, String s) {
        DouYinVideoVo douYinVideoVo = DouYinVideoVo.getInstance();
        douYinVideoVo.setVideoId(videoId);
        douYinVideoVo.setUrl(s);
        douYinVideoVo.setExtracting(false);
        douYinVideoVo.setExtractProgress(100);
        douYinVideoVo.setExtractStep(3);
        douYinVideoVo.setExtractStatus("抖音提取成功!");
        douYinVideoVo.setOldUrl(s);
        redisUtil.hset(CacheConstants.DOUYIN_CREATE_HASH +userId,videoId, JSONObject.toJSONString(douYinVideoVo));//hash存视频的详情信息,已完成
    }

    @Override
    public List<DouYinVideoVo> listDouYinVideoByUserId(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        List<Object> objectList = redisUtil.lGet(CacheConstants.DOUYIN_CREATE + userId, 0, -1);
        ArrayList<DouYinVideoVo> douYinVideoVoArrayList = new ArrayList<>();
        for (Object o : objectList) {
            Object hget = redisUtil.hget(CacheConstants.DOUYIN_CREATE_HASH + userId, (String) o);
            // 直接解析从 Redis 获取的字符串
            if (hget != null) {
                DouYinVideoVo douYinVideoVo = JSONObject.parseObject((String) hget, DouYinVideoVo.class);

                    douYinVideoVo.setExtractProgress(douYinVideoVo.getExtractProgress() + 10);
                    if (douYinVideoVo.getExtractProgress() >= 50 && douYinVideoVo.getExtractProgress() < 100) {
                        douYinVideoVo.setExtractStep(1);
                    }else if(douYinVideoVo.getExtractProgress() >= 100){
                        douYinVideoVo.setExtractProgress(100);
                        douYinVideoVo.setExtractStep(2);
                    }
                    douYinVideoVoArrayList.add(douYinVideoVo);
                    redisUtil.hset(CacheConstants.DOUYIN_CREATE_HASH + userId,douYinVideoVo.getVideoId(),JSONObject.toJSONString(douYinVideoVo));
            }
        }
        return douYinVideoVoArrayList;
    }

    @Override
    public Object listDouYinVideoById(HttpServletRequest request, String videoId) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        Object hgetted = redisUtil.hget(CacheConstants.DOUYIN_CREATE + userId, videoId);
        return hgetted;
    }

//    static final String pythonScriptPath = "D:\\idea_work_temp\\20241219zhicheng\\spy\\python\\爬取抖音单个视频.py";
       static final String pythonScriptPath = "/mnts/jar_work/LiTui/qywechat/douyin_video.py";
    public static boolean checkPythonScriptExists() {
        File scriptFile = new File(pythonScriptPath);
        if (scriptFile.exists()) {
            System.out.println("Python脚本存在: " + scriptFile.getAbsolutePath());
            return true;
        } else {
            System.out.println("Python脚本不存在: " + scriptFile.getAbsolutePath());
            return false;
        }
    }
    @Async
    @Override
    public  String extractAudioFromVideo(String userId,String videoPath,String videoId) {

        Process process = null;
        try {
            // 先检查脚本是否存在
            if (!checkPythonScriptExists()) {
                return "错误: 抖音Python脚本不存在";
            }
            // 使用ProcessBuilder更安全
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "python3",
                    pythonScriptPath,
                    videoPath
            );

            // 设置工作目录（可选）
            // processBuilder.directory(new File("/path/to/working/directory"));

            // 合并错误流到标准输出
            processBuilder.redirectErrorStream(true);

            // 启动进程
            process = processBuilder.start();

            // 读取输出
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)
            );

            DouYinVideoVo douYinVideoVo = DouYinVideoVo.getInstance();
            douYinVideoVo.setVideoId(videoId);
            douYinVideoVo.setUrl("");
            douYinVideoVo.setExtracting(true);
            douYinVideoVo.setExtractProgress(50);
            douYinVideoVo.setExtractStep(1);
            redisUtil.hset(CacheConstants.DOUYIN_CREATE_HASH +userId,videoId, JSONObject.toJSONString(douYinVideoVo));//hash存视频的详情信息,已完成
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("抖音Python输出: " + line);
                // 检查成功标志
                if (line.startsWith("SUCCESS:")) {
                    String extractedPath = line.substring(8);
                    int exitCode = process.waitFor();
                     if (exitCode == 0) {
                        //异步保存起来
                         saveDouYinVideo(userId,videoId,extractedPath);
//                        System.out.println("输出成功后上传二进制给阿里云录音文件...."+extractedPath);
                        return extractedPath;
                    } else {
                        throw new RuntimeException("Python脚本异常退出，代码: " + exitCode);
                    }
                }
            }
            // 也要读取错误流，避免进程阻塞
            BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8)
            );
            String errorLine;
            while ((errorLine = errorReader.readLine()) != null) {
                System.err.println("Python错误: " + errorLine);
            }
            // 等待进程完成
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("音频提取失败，退出码: " + exitCode);
            }

        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("执行音频提取失败: " + e.getMessage(), e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }

        throw new RuntimeException("音频提取未返回成功结果");
    }
}
